import React, { useState, useEffect } from 'react';
import classnames from 'classnames';
import moment from 'moment';
import { connect } from 'dva';
import { Button, Form, Select, Table, Empty, Modal, message } from 'antd';
import TPage from '@/modules/TPage';
import CreateModal from './CreateModal';
import Service from '@/public/http/services';
import { OnOrOffState, FileType, FileTypeClass } from '@/public/constant/enums';
import style from './index.css';
const { Option } = Select;
const { Column } = Table;
const List: React.FC<any> = ({ nameSpace, title, moduleId, moduleType, total, list, dispatch }) => {
    const [curPage, setCurPage] = useState(1);
    const [curName, setCurName] = useState(null);
  const [aihao, setAihao] = useState([]);
    const pageSize = 10;
    /**
     * 加载列表数据
     */
    function fetchList({ page, name }) {
        dispatch({
            type: `${nameSpace}/fetchList`,
            payload: {
                name,
                moduleId,
                page,
                pageSize
            }
        })
    }

    /**
     * @desc 操作完更新列表
     */
    function reFetchList() {
        fetchList({
            page: curPage,
            name: curName
        })
    }
  function getinterest(){
    Service.queryAllAihao().then((res) => {
      setAihao(res as any)
    })
  }

    useEffect(({ page = curPage, name = curName } = {}) => {
        fetchList({ page, name })
        getinterest()
    }, [curPage, curName])
    // 渲染列表查询表单

    const handleQuery = (query) => {
        setCurPage(1);
        setCurName(query);
    }

    function renderTableForm() {
        const WrappedForm = Form.create<any>({ name: 'tableForm' })(function ({ form }) {
            const { getFieldDecorator } = form as any;
            return (
                <Form onSubmit={handleQuery.bind(null, form)} layout={'inline'}>

                </Form>
            );
        })
        return (
            <WrappedForm />
        );
    }

    // 根据渲染类型渲染列表
    const renderActions =
        (record: any) => {
            const state = record.state;
            return (
                <>
                    {
                        state !== 2 ? <>
                            <Button className={style.mr8} type={'ghost'} onClick={() => { handleOnline(record); }}>上架</Button>
                            <Button className={style.mr8} type={'danger'} onClick={() => { handleDelete(record); }}>删除</Button>
                        </>
                            :
                            <Button className={style.mr8} type={'ghost'} onClick={() => { handleOffnline(record); }}>下架</Button>
                    }
                </>
            );
        }

    const [formModalVisible, setFormModalVisible] = useState(false);
    const [curModalStatus, setCurModalStatus] = useState(0);

    /**
     *
     * @desc 创建
     */
    const handleCreate = () => {
        setCurModalStatus(0);
        setFormModalVisible(true);
    }

    const [curEditInfo, setCurEditInfo] = useState({})
    /**
     *
     * @desc 编辑
     */
    const handleEdit = (record) => {
        setCurModalStatus(1);
        setCurEditInfo(record);
        setFormModalVisible(true);
    }

    /**
     * @desc 创建提交
     */
    const handleSubmit = (form: any, { authorPortraits, urls, coverImgs, summary,moduleId }, type) => {
      const { validateFields, resetFields } = form;
      const status = type;
      validateFields((err, value) => {
        if (!err) {
          const { name, type, author, keywords,description } = value;
          const params = {
            coverImg: (coverImgs[0] as any).url,
            authorPortrait: (authorPortraits[0] as any).url,
            url: (urls[0] as any).url,
            name,
            type,
            author,
            keywords,
            summary,
            moduleId,
            tags:form.tags,
            description
          };

          Service.createTreasureBox(params).then(() => {
            message.info(`${type ? '添加' : '修改'}成功`);
            resetFields();
            setCurEditInfo({});
            setFormModalVisible(false);
            reFetchList();
          })
        }
      })
    }

    /**
     *
     * @desc 创建/编辑取消
     */
    const handleCancel = (form) => {
        form.resetFields();
        setCurEditInfo({});
        setFormModalVisible(false);
    }

    /**
     * @desc 删除
     */
    const handleDelete = ({ id }) => {
        Modal.confirm({
            title: '确定要将该文件删除吗？',
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
                Service.deleteTreasureBox({
                    id
                }).then(() => {
                    message.info('删除成功');
                    reFetchList();
                })
            }
        });
    }

    /**
     * @desc 上架
     */
    const handleOnline = ({ id }) => {
        Modal.confirm({
            title: '确定上架吗？',
            okText: '上架',
            cancelText: '取消',
            onOk: () => {
                Service.onlineTreasureBox({ id }).then(() => {
                    message.info('上架成功');
                    reFetchList();
                })
            }
        });
    }

    /**
     * @desc 下架
     */
    const handleOffnline = ({ id }) => {
        Modal.confirm({
            title: '确定下架吗？',
            okText: '下架',
            cancelText: '取消',
            onOk: () => {
                Service.offlineTreasureBox({ id }).then(() => {
                    message.info('下架成功');
                    reFetchList();
                })
            }
        });
    }

    return (
        <TPage>
            <TPage.Title>{title}</TPage.Title>
            <TPage.Table>
                <TPage.Layout className={style.btns}>
                    <Button type={'primary'} onClick={handleCreate}>新建</Button>
                    <TPage.Search
                        placeholder={'请输入文件名称，可按回车键搜索'}
                        onSearch={handleQuery}
                    />
                </TPage.Layout>
                <Table
                    className={classnames(style.mt16, style.box_list)}
                    locale={{ emptyText: <Empty description={'无数据'} /> }}
                    dataSource={list}
                    pagination={{ total, current: curPage, pageSize, onChange: setCurPage }}
                    rowKey={(record: any) => record.id}
                    scroll={{ x: 2000 }}
                >
                    <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
                    <Column title={'文件名'} dataIndex={'filename'} key={'filename'} width={220}
                        render={(value, record: any) => {
                            return <span style={{ fontWeight: 600}} className={style.mainPicUnit}>
                                {record.filename}
                            </span>
                        }} />
                    <Column title={'所属专栏'} width={280} dataIndex={'moduleName'} key={'moduleName'} render={value => <span className={style.moduleName}>{value}</span>}/>
                    <Column title={'文件格式'} dataIndex={'fileType'} key={'fileType'} render={value => <span className={style[FileTypeClass[value]]}>{FileType[value]}</span>}/>
                    <Column title={'文件大小(MB)'} dataIndex={'fileSize'} key={'fileSize'} />
                    <Column title={'标签'} width={280} dataIndex={'tags'} key={'tags'} render={value => <span className={style.moduleName}>{value}</span>}/>
                    <Column title={'关键词'} dataIndex={'keyword'} key={'keyword'} />
                    <Column title={'下载量'} dataIndex={'downloadNum'} key={'downloadNum'} />
                    <Column title={'状态'} width={100} dataIndex={'state'} key={'state'} render={(value) => <span className={style[value === 1 ? 'offline' : 'online']}>{OnOrOffState[value]}</span>} />
                    <Column title={'更新时间'} dataIndex={'uTime'} key={'uTime'} width={200} render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
                    <Column title={'创建时间'} dataIndex={'cTime'} key={'cTime'} width={200} render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
                    <Column title={'操作'} key={'act'} fixed={'right'} render={renderActions} />
                </Table>
            </TPage.Table>
            <CreateModal visible={formModalVisible}
                title={curModalStatus === 0 ? '文件创建' : '文件编辑'}
                formData={curModalStatus === 0 ? {} : curEditInfo}
                moduleType={moduleType}
                moduleId={moduleId}
                interlist={aihao}
                onOK={(form, data) => handleSubmit(form, data, curModalStatus === 0)}
                onCancel={handleCancel} />

        </TPage>
    );
}
export default List;
